package poc;

import org.docx4j.TextUtils;
import org.docx4j.XmlUtils;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.toc.TocHelper;
import org.docx4j.wml.*;
import poc.utils.ParagraphUtil;
import poc.utils.RunUtil;

import javax.xml.bind.JAXBElement;
import java.io.File;
import java.math.BigInteger;
import java.util.List;


public class Main {
	private  static ObjectFactory wmlObjectFactory = new ObjectFactory();

	public static void main(String[] args) throws Exception {

		String newerfilepath = System.getProperty("user.dir") + "/poc_develop/source_1.docx";

		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new File(newerfilepath));
		List<Object> paragraphs = TocHelper.getAllElementsFromObject(wordMLPackage.getMainDocumentPart(), P.class);

		//Pre-Processing
		for (Object p : paragraphs) {
			List<R> footnoteRuns= RunUtil.getRuns(p,"footnoteReference");
			for (R footnoteRun:footnoteRuns){
				BigInteger value=null;
				List<Object> childs= footnoteRun.getContent();
				for (Object child :childs){
					if (child instanceof JAXBElement){
						JAXBElement element=(JAXBElement)child;
						if (element.getName().getLocalPart().equals ("footnoteReference")){
							CTFtnEdnRef ctFtnEdnRef=(CTFtnEdnRef)element.getValue();
							value=ctFtnEdnRef.getId();
						}
					}
				}
				Text t = wmlObjectFactory.createText();
				t.setValue("#"+value.intValue()+"#");
				JAXBElement<org.docx4j.wml.Text> textWrapped = wmlObjectFactory.createRT(t);
				footnoteRun.getContent().add(textWrapped);
			}
		}


		for (Object p : paragraphs) {
			if (XmlUtils.marshaltoString(p).contains("<w:pict>")){
//				System.out.println(XmlUtils.marshaltoString(p));
				List<P> pictPList= ParagraphUtil.getAllPInPicture(p);
				for (P pictP :pictPList){
					System.out.println("paragraph text:" +TextUtils.getText(pictP));
					Paragraph.trans(pictP);
				}
			}else {
				String pText= TextUtils.getText(p);
				System.out.println("paragraph text:" +pText);
				Paragraph.trans((P)p);
			}
		}
		for (Object p : ParagraphUtil.getFootNotesParagraphs(wordMLPackage.getMainDocumentPart())) {
			Paragraph.trans((P)p);
		}
		String filename = System.getProperty("user.dir") +  "/poc_develop/result_1.docx";
		wordMLPackage.save(new java.io.File(filename) );
	}

}


